<template>
  <div class="home-container">
    <el-row :gutter="20" style="margin-top: 20px;">
      <!-- 左侧内容区域（学生视角完整） -->
      <el-col :span="16">
        <!-- 学生快捷功能与信息概览（已内联） -->
        <el-row :gutter="20" style="margin-bottom: 20px;">
          <el-col :span="6">
            <el-card class="function-card" @click="navigateTo('/main/query')">
              <div class="function-content">
                <el-icon size="32" color="#67c23a">
                  <Search />
                </el-icon>
                <h3>信息查询</h3>
                <p>查询个人信息、成绩等</p>
              </div>
            </el-card>
          </el-col>

          <el-col :span="6">
            <el-card class="function-card" @click="navigateTo('/main/leave')">
              <div class="function-content">
                <el-icon size="32" color="#e6a23c">
                  <Document />
                </el-icon>
                <h3>请假申请</h3>
                <p>提交请假申请</p>
              </div>
            </el-card>
          </el-col>

          <el-col :span="6">
            <el-card class="function-card" @click="navigateTo('/main/scholarship')">
              <div class="function-content">
                <el-icon size="32" color="#f56c6c">
                  <Trophy />
                </el-icon>
                <h3>奖学金</h3>
                <p>奖学金申请与查询</p>
              </div>
            </el-card>
          </el-col>

          <el-col :span="6">
            <el-card class="function-card" @click="navigateTo('/main/course')">
              <div class="function-content">
                <el-icon size="32" color="#909399">
                  <Reading />
                </el-icon>
                <h3>选课</h3>
                <p>课程选择与管理</p>
              </div>
            </el-card>
          </el-col>
        </el-row>

        <!-- 个人信息概览 -->
        <el-card style="margin-bottom: 20px;">
          <template #header>
            <span>个人信息概览</span>
          </template>
          <div class="info-overview">
            <div class="info-item">
              <span class="label">学号：</span>
              <span class="value">{{ (studentInfo && studentInfo.studentNum) || '-' }}</span>
            </div>
            <div class="info-item">
              <span class="label">姓名：</span>
              <span class="value">{{ (studentInfo && studentInfo.name) || '-' }}</span>
            </div>
            <div class="info-item">
              <span class="label">专业：</span>
              <span class="value">{{ (studentInfo && studentInfo.grade) || '-' }}</span>
            </div>
            <div class="info-item">
              <span class="label">班级：</span>
              <span class="value">{{ (studentInfo && studentInfo.className) || '-' }}</span>
            </div>
            <div class="info-item">
              <span class="label">辅导员：</span>
              <span class="value">{{ (studentInfo && studentInfo.counselor) || '-' }}</span>
            </div>
          </div>
        </el-card>

        <!-- 通知公告（保留学生视角） -->
        <el-card>
          <template #header>
            <div class="card-header">
              <span>通知公告</span>
              <el-button type="text" @click="navigateTo('/main/query')">更多</el-button>
            </div>
          </template>
          <el-timeline>
            <el-timeline-item timestamp="2024-01-15" placement="top">
              <el-card>
                <h4>关于2024年春季学期选课通知</h4>
                <p>请同学们及时完成选课，选课截止时间为1月20日。</p>
              </el-card>
            </el-timeline-item>
            <el-timeline-item timestamp="2024-01-10" placement="top">
              <el-card>
                <h4>奖学金申请开始</h4>
                <p>2024年度奖学金申请现已开始，请符合条件的同学及时申请。</p>
              </el-card>
            </el-timeline-item>
          </el-timeline>
        </el-card>
      </el-col>

      <!-- 右侧内容区域（学生与非学生共用） -->
      <el-col :span="8">
        <!-- 自定义日历组件 -->
        <el-card class="calendar-card" style="margin-bottom: 20px;">
          <div class="custom-calendar">
            <!-- 日历头部 -->
            <div class="calendar-header">
              <div class="calendar-title">
                {{ formatCalendarTitle(calendarValue) }}
              </div>
              <div class="calendar-controls">
                <button class="nav-btn" @click="previousMonth">‹</button>
                <button class="nav-btn" @click="goToToday">今天</button>
                <button class="nav-btn" @click="nextMonth">›</button>
              </div>
            </div>

            <!-- 星期标题 -->
            <div class="weekdays">
              <div v-for="day in weekdays" :key="day" class="weekday">{{ day }}</div>
            </div>

            <!-- 日期网格 -->
            <div class="calendar-grid">
              <div
                v-for="day in calendarDays"
                :key="`${day.date}-${day.day}`"
                class="calendar-day"
                :class="{
                  'is-current-month': day.isCurrentMonth,
                  'is-today': day.isToday,
                  'is-selected': day.isSelected,
                  'has-event': day.hasEvent
                }"
                @click="selectDate(day)"
              >
                <span class="day-number">{{ day.day }}</span>
                <div v-if="day.hasEvent" class="event-dot"></div>
              </div>
            </div>
          </div>
        </el-card>

        <!-- 即将到来的事件 -->
        <el-card>
          <template #header>
            <div class="card-header">
              <span>即将到来的事件</span>
            </div>
          </template>
          <div class="upcoming-events">
            <div v-for="event in upcomingEvents" :key="event.id" class="event-item">
              <div class="event-content">
                <div class="event-title">{{ event.title }}</div>
                <div class="event-description">{{ event.description }}</div>
                <div class="event-meta">
                  <span class="event-date">{{ event.date }}</span>
                  <span class="event-duration">{{ event.duration }}</span>
                </div>
              </div>
              <div class="event-icon">
                <el-icon color="#409eff">
                  <Document />
                </el-icon>
              </div>
            </div>
            <div class="view-all-link">
              <el-button type="text" style="color: #e6a23c;">查看所有即将到来的事件 ></el-button>
            </div>
          </div>
        </el-card>
      </el-col>
    </el-row>
  </div>
</template>

<script setup lang="ts">
import { ref, computed, onMounted } from 'vue'
import { useRouter } from 'vue-router'
import { Document, Search, Trophy, Reading } from '@element-plus/icons-vue'
import { getStudentById } from '@/api/studentInfo'

const props = defineProps<{ studentInfo: any }>()

// 学生信息本地状态：优先使用上层传入的 props，否则组件内部拉取
const studentInfo = ref<any>(props.studentInfo || null)

// 拉取学生信息（从 localStorage 读取 userId 调用接口）
const fetchStudentInfo = async () => {
  try {
    const raw = localStorage.getItem('userInfo')
    if (!raw) {
      ElMessage.warning('请先登录')
      return
    }
    const userInfo = JSON.parse(raw || '{}')
    const userId = Number(userInfo?.userId)
    if (!userId) {
      ElMessage.warning('用户信息缺失，请重新登录')
      return
    }

    const res = await getStudentById(userId)
    // 兼容后端返回 code 为 '200' 或 '0' 表示成功
    if ((res.code === '200' || res.code === '0') && res.data) {
      studentInfo.value = res.data
    } else {
      ElMessage.error(res.msg || '获取学生信息失败')
    }
  } catch (e) {
    ElMessage.error('获取学生信息异常，请稍后重试')
  }
}

onMounted(() => {
  if (!studentInfo.value) {
    fetchStudentInfo()
  }
})

const router = useRouter()
const navigateTo = (path: string) => {
  router.push(path)
}

// 日历相关数据
const calendarValue = ref(new Date())
const selectedDate = ref(new Date())
const weekdays = ['一', '二', '三', '四', '五', '六', '日']

// 即将到来的事件数据
const upcomingEvents = ref([
  { id: 1, title: '心理学考试', description: '在学校进行笔试考试', date: '19 Jan', duration: '45 分钟' },
  { id: 2, title: '数学理论', description: '在学校进行总结写作', date: '20 - 21 Jan', duration: '3 小时' },
  { id: 3, title: '文学考试', description: '在学校进行笔试考试', date: '22 Jan', duration: '50 分钟' }
])

const eventDates = ['2024-01-19', '2024-01-20', '2024-01-21', '2024-01-22']

const hasEvent = (date: string | undefined) => {
  if (!date) return false
  try {
    const dateObj = new Date(date)
    const formattedDate = dateObj.toISOString().split('T')[0]
    return formattedDate ? eventDates.includes(formattedDate) : false
  } catch (error) {
    console.warn('Invalid date format:', date)
    return false
  }
}

const calendarDays = computed(() => {
  const year = calendarValue.value.getFullYear()
  const month = calendarValue.value.getMonth()
  const today = new Date()

  const firstDay = new Date(year, month, 1)
  const lastDay = new Date(year, month + 1, 0)
  const firstDayOfWeek = (firstDay.getDay() + 6) % 7
  const prevMonth = new Date(year, month, 0)
  const prevMonthDays = prevMonth.getDate()

  const days: any[] = []

  for (let i = firstDayOfWeek - 1; i >= 0; i--) {
    const day = prevMonthDays - i
    const date = new Date(year, month - 1, day)
    days.push({
      day,
      date: date.toISOString().split('T')[0],
      isCurrentMonth: false,
      isToday: false,
      isSelected: false,
      hasEvent: hasEvent(date.toISOString().split('T')[0])
    })
  }

  for (let day = 1; day <= lastDay.getDate(); day++) {
    const date = new Date(year, month, day)
    const dateStr = date.toISOString().split('T')[0]
    const isToday = date.toDateString() === today.toDateString()
    const isSelected = date.toDateString() === selectedDate.value.toDateString()

    days.push({
      day,
      date: dateStr,
      isCurrentMonth: true,
      isToday,
      isSelected,
      hasEvent: hasEvent(dateStr)
    })
  }

  const remainingDays = 42 - days.length
  for (let day = 1; day <= remainingDays; day++) {
    const date = new Date(year, month + 1, day)
    days.push({
      day,
      date: date.toISOString().split('T')[0],
      isCurrentMonth: false,
      isToday: false,
      isSelected: false,
      hasEvent: hasEvent(date.toISOString().split('T')[0])
    })
  }

  return days
})

const formatCalendarTitle = (date: any) => {
  if (!date) return '未知日期'
  try {
    const dateObj = date instanceof Date ? date : new Date(date)
    const year = dateObj.getFullYear()
    const month = dateObj.getMonth() + 1
    return `${year}年${month}月`
  } catch (error) {
    console.warn('Invalid date format:', date)
    return '未知日期'
  }
}

const previousMonth = () => {
  const newDate = new Date(calendarValue.value)
  newDate.setMonth(newDate.getMonth() - 1)
  calendarValue.value = newDate
}

const nextMonth = () => {
  const newDate = new Date(calendarValue.value)
  newDate.setMonth(newDate.getMonth() + 1)
  calendarValue.value = newDate
}

const goToToday = () => {
  const today = new Date()
  calendarValue.value = today
  selectedDate.value = today
}

const selectDate = (day: any) => {
  if (day.isCurrentMonth) {
    selectedDate.value = new Date(day.date)
  }
}
</script>

<style scoped>
.home-container {
  padding: 0;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

/* 日历卡片样式 */
.calendar-card {
  background: #fff;
  border: 1px solid #e4e7ed;
  border-radius: 8px;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.1);
}

.calendar-card :deep(.el-card__header) {
  background: #f5f7fa;
  border-bottom: 1px solid #e4e7ed;
  color: #303133;
  font-weight: 600;
}

.calendar-card :deep(.el-card__body) {
  padding: 0;
  background: #fff;
}

.custom-calendar {
  background: #fff;
  border-radius: 8px;
  overflow: hidden;
}

.calendar-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 16px 20px;
  background: #f8f9fa;
  border-bottom: 1px solid #e4e7ed;
}

.calendar-title {
  font-size: 16px;
  font-weight: 600;
  color: #303133;
}

.calendar-controls {
  display: flex;
  gap: 8px;
  align-items: center;
}

.nav-btn {
  background: #fff;
  border: 1px solid #dcdfe6;
  color: #606266;
  font-size: 14px;
  padding: 6px 12px;
  border-radius: 4px;
  cursor: pointer;
  transition: all 0.3s;
  min-width: 32px;
  height: 32px;
  display: flex;
  align-items: center;
  justify-content: center;
}

.nav-btn:hover {
  background: #f5f7fa;
  border-color: #c0c4cc;
  color: #409eff;
}

.nav-btn:active {
  background: #ecf5ff;
  border-color: #409eff;
}

.weekdays {
  display: grid;
  grid-template-columns: repeat(7, 1fr);
  background: #f8f9fa;
  border-bottom: 1px solid #e4e7ed;
}

.weekday {
  padding: 12px 0;
  text-align: center;
  font-size: 14px;
  font-weight: 500;
  color: #909399;
  border-right: 1px solid #e4e7ed;
}

.weekday:last-child {
  border-right: none;
}

.calendar-grid {
  display: grid;
  grid-template-columns: repeat(7, 1fr);
  background: #fff;
}

.calendar-day {
  position: relative;
  height: 40px;
  display: flex;
  align-items: center;
  justify-content: center;
  cursor: pointer;
  transition: all 0.3s ease;
  border-right: 1px solid #f0f0f0;
  border-bottom: 1px solid #f0f0f0;
  font-size: 14px;
  color: #606266;
}

.calendar-day:nth-child(7n) {
  border-right: none;
}

.calendar-day:hover {
  background: #f5f7fa;
}

.calendar-day.is-current-month {
  color: #303133;
  font-weight: 500;
}

.calendar-day:not(.is-current-month) {
  color: #c0c4cc;
  background: #fafafa;
}

.calendar-day.is-today {
  color: #409eff;
  font-weight: 600;
}

.calendar-day.is-today:not(.is-selected) {
  background: #ecf5ff;
}

.calendar-day.is-selected {
  background: #409eff;
  color: #fff;
  font-weight: 600;
}

.calendar-day.is-selected:hover {
  background: #337ecc;
}

.calendar-day.has-event {
  position: relative;
}

.calendar-day.has-event:not(.is-selected) {
  background: #fff7e6;
}

.calendar-day.has-event.is-selected {
  background: #409eff;
}

.day-number {
  font-size: 14px;
  line-height: 1;
}

.event-dot {
  position: absolute;
  bottom: 4px;
  left: 50%;
  transform: translateX(-50%);
  width: 4px;
  height: 4px;
  background-color: #e6a23c;
  border-radius: 50%;
}

.calendar-day.is-selected .event-dot {
  background-color: #fff;
}

.upcoming-events {
  max-height: 400px;
  overflow-y: auto;
}

.event-item {
  display: flex;
  align-items: flex-start;
  padding: 12px 0;
  border-bottom: 1px solid #f0f0f0;
}

.event-item:last-child {
  border-bottom: none;
}

.event-content {
  flex: 1;
  margin-right: 12px;
}

.event-title {
  font-weight: 600;
  color: #303133;
  margin-bottom: 4px;
  font-size: 14px;
}

.event-description {
  color: #909399;
  font-size: 12px;
  margin-bottom: 6px;
  line-height: 1.4;
}

.event-meta {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.event-date {
  color: #e6a23c;
  font-size: 12px;
  font-weight: 500;
}

.event-duration {
  color: #909399;
  font-size: 11px;
}

.event-icon {
  display: flex;
  align-items: center;
  justify-content: center;
  width: 24px;
  height: 24px;
  background-color: #f0f9ff;
  border-radius: 50%;
}

.view-all-link {
  text-align: center;
  margin-top: 12px;
  padding-top: 12px;
  border-top: 1px solid #f0f0f0;
}

/* 学生快捷功能与信息概览样式（来自 StudentPanel） */
.function-card {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  cursor: pointer;
  transition: all 0.3s;
  height: 100px;
  padding: 0;
}

.function-card:hover {
  transform: translateY(-2px);
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
}

.function-content {
  text-align: center;
  padding: 12px 5px;
  height: 100%;
  display: flex;
  flex-direction: column;
  justify-content: center;
  align-items: center;
}

.function-content h3 {
  margin: 8px 0 3px 0;
  color: #303133;
  font-size: 14px;
}

.function-content p {
  margin: 0;
  color: #909399;
  font-size: 11px;
  line-height: 1.3;
}

.info-overview {
  padding: 10px 0;
}

.info-item {
  display: flex;
  margin-bottom: 12px;
  align-items: center;
}

.label {
  width: 80px;
  color: #606266;
  font-weight: 500;
}

.value {
  color: #303133;
  flex: 1;
}
</style>